﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Linq;

namespace SkypeBot.Core.Dictionaries
{
    class Dictionaries : IResult
    {
        MongoDatabase mobjDataBase;

        public Dictionaries()
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            mobjDataBase = server.GetDatabase("SentenceDictionary");
        }

        public Responce GetResult(Message objMessage)
        {
            try
            {
                string strResult = string.Empty;
                DataModel dm = null;
                var collection = mobjDataBase.GetCollection("HelloDictionary");
                IEnumerable<DataModel> result = collection.FindAllAs<DataModel>();
                foreach (var item in result)
                {
                    foreach (var it in item.Keys)
                    {
                        string regEx = string.Format("^(|.* ){0}(({1}| ).*|)$", it, @"\p{P}");
                        Regex reg = new Regex(regEx, RegexOptions.IgnoreCase);
                        if (reg.Match(objMessage.MessageContent).Success)
                        {
                            dm = item;
                            break;
                        }
                    }

                    break;
                }

                if (dm != null)
                {
                    Random random = new Random();
                    int intNumber = random.Next(dm.Answers.Count);
                    strResult = dm.Answers[intNumber];
                }

                return new Responce(strResult);
            }
            catch (Exception ex) { return new Responce(string.Empty); }
        }
    }
}
